<template>
  <div class="container">
    <!-- 左侧锚点导航 -->
    <div class="anchor-nav">
      <el-anchor
        :container="containerRef"
        direction="vertical"
        type="default"
        :default-active="defaultAnchor"
        :offset="20"
        text-color="#fff"
        active-color="#ff9800"
        style="width: 100%; background-color: transparent; padding: 10px 0;"
      >
        <el-anchor-link
          v-for="item in menuItems"
          :key="item.id"
          :href="item.href"
          :title="item.name"
          class="custom-anchor-link"
          @click.prevent="handleAnchorClick(item)"
        />
      </el-anchor>
    </div>

    <!-- 右侧内容展示区域 -->
    <div class="content-display">
      <div ref="containerRef" class="anchor_body">
        <div
          v-for="item in menuItems"
          :key="item.id"
          :id="item.href.slice(1)"
        >
          <!-- 场景标题和描述 -->
          <div v-if="item.id != 'large-model-config'" class="scenario-header">
            <span style="cursor: default;font-size: 1rem;">{{ item.name }}</span>
            <div class="separator"> —— </div>
            <div style="cursor: default;font-size: 1rem;">{{ item.description }}</div>
          </div>

          <!-- 算法展示网格 -->
          <div class="grid-container">
            <div
              class="grid-item"
              v-for="(algorithm, index) in paddedAlgorithms(item.algorithms)"
              :key="index"
            >
              <template v-if="algorithm">
                <div style="cursor: pointer" class="image-container" @click="navigateToDetails(algorithm)">
                  <img :src="algorithm.coverUrl" alt="Algorithm Cover" />
                </div>
                <div class="description">
                  <div class="title">{{ algorithm.name }}</div>
                  <div style="margin-top: 10px;">{{ algorithm.description }}</div>
                </div>
              </template>
              <template v-else>
                <div class="image-container1">
                  <img style="position: absolute;top: 50%;transform: translateY(-50%); width: 100%;height: auto;" src="../assets/image/waiting.png" alt="Algorithm Cover" />
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { useAlgorStore } from "@/stores/algorothm";
import request from "@/utils/request";

// Refs 和路由
const containerRef = ref<HTMLElement | null>(null);
const router = useRouter();

// Store 数据
const algorStore = useAlgorStore();

// 格式化菜单项（修改后的版本）
const formattedMenuItems = computed(() => {
  const baseItems = AllAlgorithmAndAlgorithmScenario.value?.map((item: any, index: number) => ({
    id: item.scenario.id || "N/A",
    name: item.scenario.scenarioName || "未知场景",
    description: item.scenario.scenarioDescription || "无描述",
    href: `#part${index}`,
    algorithms: item.algorithms.map((algorithm: any) => ({
      id: algorithm?.algorithm?.id || "N/A",
      scenarioID: algorithm?.algorithm?.scenarioID || "N/A",
      name: algorithm?.algorithm?.algorithmName || "未知算法",
      coverUrl: algorithm?.algorithm?.coverUrl || "",
      description: algorithm?.algorithm?.description || "无描述",
      exampleUrl: algorithm?.algorithm?.exampleUrl || "",
      images: algorithm?.images || [],
      result: algorithm?.algorithm?.algorithmResult || '',
    })),
  })) || [];

  // 添加大模型配置特殊菜单项
  if (AllAlgorithmAndAlgorithmScenario.value?.largeModel) {
    baseItems.push({
      id: 'large-model-config',
      name: AllAlgorithmAndAlgorithmScenario.value.largeModel.algorithmName,
      description: AllAlgorithmAndAlgorithmScenario.value.largeModel.algorithmDesc,
      href: '#largeModelConfig',
      isSpecial: true, // 标记为特殊菜单项
      algorithms: []
    });
  }

  return baseItems;
});

// 菜单项
const menuItems = formattedMenuItems;

// 默认选中第一条
const defaultAnchor = ref("#part0");

// 动态补齐算法
const paddedAlgorithms = (algorithms: any) => {
  const remainder = algorithms.length % 3;
  if (remainder === 0) return algorithms;
  const placeholders = 3 - remainder;
  return [...algorithms, ...Array(placeholders).fill(null)];
};

// 处理锚点点击
const handleAnchorClick = (item: any) => {
  if (item.isSpecial) {
    // 特殊菜单项点击处理 - 跳转到大模型配置页面
    router.push({
      path: "/bigModel",
      query: {
        scenarioID: bigModel.value.id,
        name: bigModel.value.algorithmName,
        description: bigModel.value.algorithmDesc,
        scenarioName:bigModel.value.scenarioName
      },
    });
  } else {
    // 普通菜单项保持原有滚动行为
    defaultAnchor.value = item.href;
    const element = document.getElementById(item.href.slice(1));
    if (element) {
      containerRef.value?.scrollTo({
        top: element.offsetTop - 20,
        behavior: 'smooth'
      });
    }
  }
};

// 跳转到算法详情页
const navigateToDetails = (algorithm: any) => {
  if (algorithm.result) {  
    const result = JSON.stringify(algorithm.result);
    router.push({
      path: "/algorithmsMessage",
      query: {
        result: result,
        scenarioID: algorithm.id,
        exampleUrl: algorithm.exampleUrl,
      },
    });
  } else {
    router.push({
      path: "/algorithmsMessage",
      query: {
        scenarioID: algorithm.id,
        exampleUrl: algorithm.exampleUrl,
      },
    });
  }
};

// 获取算法数据
const AllAlgorithmAndAlgorithmScenario = ref();
const bigModel = ref()
const getAllAlgorithm = () => {
  request.get("/algorithm/algorithmView").then((res) => {   
    AllAlgorithmAndAlgorithmScenario.value = res.data.algorithmViews;
    if (res.data.largeModel) {
      AllAlgorithmAndAlgorithmScenario.value.largeModel = res.data.largeModel;
      bigModel.value = res.data.largeModel
      console.log(1111111,bigModel.value);
      
      
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  getAllAlgorithm();
  nextTick(() => {
    defaultAnchor.value = "#part0";

    // 监听滚动
    containerRef.value?.addEventListener("scroll", () => {
      const sections = menuItems.value
        .filter((item: any) => !item.isSpecial)
        .map((item: any) => document.getElementById(item.href.slice(1)));
      
      for (const section of sections) {
        if (section && section.getBoundingClientRect().top <= 50) {
          defaultAnchor.value = `#${section.id}`;
        }
      }
    });
  });
});
</script>

<style scoped>
/* 原有样式保持不变 */
.container {
  width: 100vw;
  height: 100%;
  display: flex;
}
.anchor-nav {
  height: 100%;
  flex: 2;
  background: linear-gradient(to right, rgba(16, 86, 111, 1), rgba(0, 0, 255, 0));
}
.content-display {
  height: 100%;
  flex: 8;
  margin-left: 1rem;
}
.anchor_body {
  height: 100%;
  overflow-y: auto;
}
.anchor_body::-webkit-scrollbar {
  display: none;
}
.el-anchor {
  --el-anchor-font-size: 18px;
  --el-anchor-color: #fff;
  --el-anchor-line-height: 30px;
}
.custom-anchor-link {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-size: 20px;
  color: #8b0d0d;
  padding: 10px 0;
  transition: all 0.3s ease;
}
.custom-anchor-link:hover {
  color: #ff9800;
}
.custom-anchor-link.is-active {
  color: #ff9800;
  font-weight: bold;
}
.scenario-header {
  display: flex;
  color: white;
  height: 30px;
  font-size: 14px;
  line-height: 30px;
  margin: 20px 0;
}
.separator {
  margin: 0 1.5rem;
  cursor: default;
}
.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}
.grid-item {
  display: inline-block;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
}
.grid-item:hover {
  transform: translate(5px, -5px);
  box-shadow: -5px 5px 10px rgba(255, 255, 255, 0.4);
}
.image-container {
  width: 100%;
}
.image-container1 {
  width: 100%;
  height: 100%;
  position: relative;
}
.image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.description {
  padding: 10px;
}
.description .title {
  font-weight: bolder;
}
</style>